package com.atguigu.tingshu.common.login;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * title:
 * author: zgl
 * date: 2024/2/25
 * description：
 */
@Aspect
@Component
public class TSLoginAdvance {
    @Autowired
    private RedisTemplate redisTemplate;

    @Around("@annotation(enableLoginAuth)")
    public Object aroundLogin(ProceedingJoinPoint joinPoint, EnableLoginAuth enableLoginAuth) throws Throwable {
        //token认证
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        if (request == null) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        String token = request.getHeader("token");
        UserInfoVo userInfoVo = null;
        if (StringUtils.isNotBlank(token)) {
            userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        }
        //必须要登录
        if (enableLoginAuth.required() && (StringUtils.isBlank(token) || userInfoVo == null)) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        if (userInfoVo != null) {
            AuthContextHolder.setUserId(userInfoVo.getId());
            AuthContextHolder.setUsername(userInfoVo.getNickname());
        }
        Object proceed = joinPoint.proceed(joinPoint.getArgs());
        //释放threadLocal
        AuthContextHolder.removeUserId();
        AuthContextHolder.removeUsername();
        return proceed;
    }
}
